package br.com.canvasForAll.ws.resource;

import java.util.Date;

import javax.ejb.EJB;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import br.com.canvasForAll.model.entity.Usuario;
import br.com.canvasForAll.model.services.interfaces.UsuarioService;
import br.com.canvasForAll.model.utils.json.JSONObject;

@Path("usuario")
public class UsuarioWS {
	
	@EJB private UsuarioService usuarioService;
	
	@GET
	@Path("/usuarioId/{id_user}")
	@Produces(MediaType.APPLICATION_JSON)
	public Usuario getUsuarioId(@PathParam("id_user") String idUser) throws Exception {
		try{
			return usuarioService.obterId(new Long(idUser));
		
		} catch (Exception e) {
			throw new WebApplicationException(Status.NOT_FOUND);
		}
	}
	
	@POST
	@Path("/addUsuario")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response addUsuario(Usuario u) throws Exception {
		try{
			Response response = null;
			
			if(u != null){
				if(verificaCamposObrigatorios(u)){
					u.setDataUltimaNotificacao(new Date());
					Usuario user = usuarioService.salvarUsuario(u);

					JSONObject json = new JSONObject();
					json.put("idIcs", user.getId());
					json.put("dataUltimaNotificacao", user.getDataUltimaNotificacao().getTime());
					
					response = Response.status(Status.OK).entity(json.toString()).build();
					
				} else
					response = Response.status(Status.BAD_REQUEST).build();

			} else
				response = Response.status(Status.BAD_REQUEST).build();
			
			return response;
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new WebApplicationException(Status.NOT_FOUND);
		}
	}
	
	private boolean verificaCamposObrigatorios(Usuario p) {
		if(p.getLogin() != null && p.getSenha() != null && p.getDataCriacao() != null && p.getDataUltimaAtualizacao() != null){
			return true;
		} else {
			return false;
		}
	}
	
}
